package com.tdx.blog_nowcoder.controller;

import com.tdx.blog_nowcoder.entity.Comment;
import com.tdx.blog_nowcoder.entity.DiscussPort;
import com.tdx.blog_nowcoder.entity.MyEvent;
import com.tdx.blog_nowcoder.utils.RedisKeyUtils;
import com.tdx.blog_nowcoder.utils.event.EventProducer;
import com.tdx.blog_nowcoder.service.CommentService;
import com.tdx.blog_nowcoder.service.DiscussPortService;
import com.tdx.blog_nowcoder.utils.ThreadHostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Date;

import static com.tdx.blog_nowcoder.constant.CommentReplyConstant.ENTITY_TYPE_COMMENT;
import static com.tdx.blog_nowcoder.constant.CommentReplyConstant.ENTITY_TYPE_REPLY;
import static com.tdx.blog_nowcoder.constant.KafkaTopicConstant.TOPIC_COMMENT;

@Controller
@RequestMapping("/comment") //comment/add/${post.id}
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private ThreadHostHolder hostHolder;

    @Autowired
    private DiscussPortService discussPortService;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping(path = "/add/{discusspostID}",method = RequestMethod.POST)
    public String addComment(@PathVariable("discusspostID") int discusspostID, Comment comment){
        comment.setUserId(hostHolder.getUser().getId());
        comment.setStatus(0);
        comment.setCreateTime(new Date());
        commentService.insertComment(comment);

        //触发评论事件
        MyEvent event = new MyEvent();
        event.setTopic(TOPIC_COMMENT);
        event.setEntityType(comment.getEntityType());
        event.setUserId(hostHolder.getUser().getId());
        event.setEntityId(comment.getEntityId());
        event.setData("postId",discusspostID); //设置帖子的ID

        //帖子拥有人的ID或者回复人的ID
        if(comment.getEntityType()==ENTITY_TYPE_COMMENT){
            DiscussPort target = discussPortService.getDiscussPostsById(comment.getEntityId());
            //帖子所拥有人
            event.setEntityUserId(target.getUserId());

            String redisKey = RedisKeyUtils.getPostScoreKey();
            redisTemplate.opsForSet().add(redisKey, discusspostID);


        } else if (comment.getEntityType()==ENTITY_TYPE_REPLY) {
            //回复人的ID（查询哪个人发的回复)
            Comment target = commentService.findCommentById(comment.getEntityId());
            event.setEntityUserId(target.getUserId());
        }

        //生产评论消息
        eventProducer.fireEvent(event);


        return "redirect:/discuss/detail/" + discusspostID;
    }
}
